package cn.edu.zafu.bigdata.x.huangxihao202211080211.StudentManagementSystem11;

import java.io.*;
import java.util.*;

public class StudentManager11{
    private static final String FILE_NAME = "students.dat";
    private Map<String, Student11> students;

    public StudentManager11() {
        students = loadStudents();
    }

    // 加载学生信息
    private Map<String, Student11> loadStudents() {
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(FILE_NAME))) {
            return (Map<String, Student11>) ois.readObject();
        } catch (FileNotFoundException e) {
            return new HashMap<>();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
            return new HashMap<>();
        }
    }

    // 保存学生信息
    private void saveStudents() {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(FILE_NAME))) {
            oos.writeObject(students);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 添加学生
    public boolean addStudent(String id, String name, String phone) {
        if (students.containsKey(id)) {
            return false; // 学号重复
        }
        students.put(id, new Student11(id, name, phone));
        saveStudents();
        return true;
    }

    // 检索学生
    public Student11 searchStudent(String id) {
        return students.get(id);
    }

    // 更新学生信息
    public boolean updateStudent(String id, String name, String phone) {
        Student11 student = students.get(id);
        if (student != null) {
            student.setName(name);
            student.setPhone(phone);
            saveStudents();
            return true;
        }
        return false;
    }

    // 删除学生信息
    public boolean deleteStudent(String id) {
        if (students.remove(id) != null) {
            saveStudents();
            return true;
        }
        return false;
    }
}